package com.io.util;

import com.io.properties.UploadProperties;
import com.io.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * The class/interface
 *
 * @author guod
 * @version 1.0 use jdk 1.8
 */
@Slf4j
@Component
public class FileUploadUtils {
    @Autowired
    private UploadProperties uploadProperties;

    /**
     * 功能描述：提取上传方法为公共方法
     *
     * @param uploadDir 上传文件目录
     * @param file      上传对象
     * @throws Exception 回显路径
     */
    private String executeUpload(String uploadDir, MultipartFile file) throws Exception {
        // 文件后缀名
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        // 上传文件名
        String filename = UUID.randomUUID() + "." + suffix;
        // 服务器端保存的文件对象
        File serverFile = new File(uploadDir + filename);
        // 将上传的文件写入到服务器端文件内
        FileUtils.copyInputStreamToFile(file.getInputStream(), serverFile);
        // 返回用户回显路径
        return uploadDir + filename;
    }

    /**
     * 功能描述：上传单个文件方法（多文件上传此处不再列举）
     *
     * @param file 前台上传的文件对象（注解请求头信息：enctype=multipart/form-data）
     * @return 结果信息
     */
    public ApiResult upload(MultipartFile file) {
        String returnPath;
        try {
            String format = new SimpleDateFormat("yyyy/MM/").format(new Date());
            String uploadDir = uploadProperties.getFilePath() + format;
            log.info("传的路径[{}]", uploadDir);
            // 如果目录不存在，自动创建文件夹
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean mkdirs = dir.mkdirs();
            }
            //调用上传方法
            returnPath = executeUpload(uploadDir, file);
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            return ApiResult.error("上传失败！");
        }
        return ApiResult.ok(returnPath);
    }


    public ApiResult uploads(MultipartFile[] file) {
        List<String> returnImages = new ArrayList<>();
        try {
            //上传目录地址
            // String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
            String uploadDir = uploadProperties.getFilePath() + "upload/";
            //如果目录不存在，自动创建文件夹
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean mkdirs = dir.mkdirs();
            }
            //遍历文件数组执行上传
            for (MultipartFile multipartFile : file) {
                if (multipartFile != null) {
                    // 调用上传方法进行图片的上传
                    String str = executeUpload(uploadDir, multipartFile);
                    returnImages.add(str);
                }
            }
        } catch (Exception e) {
            // 打印错误堆栈信息
            e.printStackTrace();
            return ApiResult.error("上传失败！");
        }
        return ApiResult.ok(returnImages);
    }


    public void imageDisplay(HttpServletResponse response) throws Exception {
        // 文件业务逻辑自行处理，替换下面
        File file = new File("/home/kaifa/resource/2019/02/18/upload/9a9bf096-ab71-48b3-93fd-b68f3ce255d6.png");
        // 进行文件下载的指定，设置强制下载不打开
        OutputStream outputStream = response.getOutputStream();
        // 设置显示图片
        response.setContentType("image/jpeg");
        // 设置缓存
        response.setHeader("Cache-Control", "max-age=604800");
        // outputStream写入到输出流
        outputStream.write(FileCopyUtils.copyToByteArray(file));
        outputStream.flush();
        outputStream.close();
    }

    public void downloadFile(HttpServletResponse response) throws IOException {
        // 文件业务逻辑自行处理，替换下面
        File file = new File("/home/kaifa/resource/2019/02/18/upload/9a9bf096-ab71-48b3-93fd-b68f3ce255d6.png");
        OutputStream outputStream = response.getOutputStream();
        // 进行文件下载的指定
        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("下载名称").getBytes("gbk"), "iso8859-1") + ".xls");
        // outputStream写入到输出流
        outputStream.write(FileCopyUtils.copyToByteArray(file));
        outputStream.flush();
        outputStream.close();
    }


    public ApiResult downloadFileByName(HttpServletResponse response, String fileName) {
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            String month = new SimpleDateFormat("yyyy/MM/").format(new Date());
            String path = uploadProperties.getFilePath() + month + fileName;
            File file = new File(path);
            OutputStream outputStream = response.getOutputStream();
            if (!file.isFile()) {
                return ApiResult.error();
            }
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8");
            outputStream.write(FileCopyUtils.copyToByteArray(file));
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ApiResult.ok();
    }
}
